package com.ecommerce.repository;

import com.ecommerce.entity.Address;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface AddressRepository extends JpaRepository<Address, Long> {
    
    // 根据用户ID查找所有地址，按创建时间降序排列
    List<Address> findByUserIdOrderByCreatedAtDesc(Long userId);
    
    // 根据用户ID查找默认地址
    Optional<Address> findByUserIdAndIsDefaultTrue(Long userId);
    
    // 根据用户ID和地址ID查找地址
    Optional<Address> findByUserIdAndId(Long userId, Long id);
    
    // 统计用户地址数量
    Long countByUserId(Long userId);
    
    // 将用户的所有地址设为非默认
    @Modifying
    @Query("UPDATE Address a SET a.isDefault = false WHERE a.userId = :userId")
    void clearDefaultAddress(@Param("userId") Long userId);
    
    // 根据用户ID删除所有地址
    @Modifying
    @Query("DELETE FROM Address a WHERE a.userId = :userId")
    void deleteByUserId(@Param("userId") Long userId);
} 